import React, { Component } from 'react'
import AddStudent from './Components/AddStudent'
import StudentList from './Components/StudentList'
import StudentTitle from './Components/StudentTitle'

class App extends Component {
  
  // 定义状态用于管理学员信息
  state = {
    studentList: [
      {
        number: '001',
        name: '琳琳',
        sex: '女',
        age: '18',
        college: '大前端',
        hobbies: ['足球']
      }
    ]
  }
  
  // 定义一个方法用于处理 studentList 状态
  addList = (student, callback) => {
    this.setState({
      studentList: [...this.state.studentList, student]
    }, () => {
      callback()
      console.log(this.state.studentList)
    })
  }
  // 删除方法
  removeStudent = (number) => {
    // 核心：利用 number 找到 studentList 当中需要被删除的项，将它从原数据中拿出
    // 最后再将处理后的数据重新 setState 给 state ，之后界面会自动更新
    // 01 拷贝数据
    const studentList = JSON.parse(JSON.stringify(this.state.studentList))
    // 02 找出删除的数据索引
    const index = studentList.findIndex(student => student.number === number)
    console.log('index',index)
    // 03 删除该条数据
    studentList.splice(index, 1)
    // 04 重新加载数据
    this.setState({studentList})
  }
  
  render() {
    return (
      <div className={'container'}>
        <StudentTitle />
        <AddStudent addList={this.addList} />
        <StudentList studentList={this.state.studentList} removeStudent={this.removeStudent}/>
      </div>
    )
  }
}
export default App